from pptx import Presentation
from pptx.dml.color import RGBColor
from openpyxl import load_workbook
from PIL import Image
# 加载现有的PPT文件
import requests
from scrapy import dir_name
from io import BytesIO
from pptx.util import Pt, Inches
prs = Presentation(r"D:\Users\lwd\Desktop\PPt\test.pptx")
file_path = fr"D:\Users\lwd\Desktop\PPt\{dir_name}\scores1.xlsx"
print(file_path)
def download_image(image_url):
    response = requests.get(image_url)
    response.raise_for_status()  # 确保请求成功
    # 打开图片
    image = Image.open(BytesIO(response.content))
    # 缩放图片
    width, height = image.size
    size = min(width, height)
    left = (width - size) // 2
    top = (height - size) // 2
    right = (width + size) // 2
    bottom = (height + size) // 2
    cropped_image = image.crop((left, top, right, bottom))

    # 调整图片大小
    width_px = int(8.33 * 72 * 0.3937)
    cropped_image_resized = cropped_image.resize((width_px, width_px), Image.Resampling.LANCZOS)

    cropped_image_stream = BytesIO()
    cropped_image_resized.save(cropped_image_stream, format='PNG')
    cropped_image_stream.seek(0)
    return cropped_image_stream

font_settings = [
    {'size': Pt(24), 'color': RGBColor(0, 0, 0)},  # 红色，18号字体
    {'size': Pt(36), 'color': RGBColor(255, 192, 0)},  # 绿色，20号字体
    {'size': Pt(16), 'color': RGBColor(0, 0, 0)},  # 蓝色，22号字体
    {'size': Pt(18), 'color': RGBColor(0, 0, 0)}  # 黄色，24号字体
]
wb = load_workbook(filename=file_path, data_only=True)
sheet = wb.active  # 默认读取第一个工作表，如果有多个工作表可以指定 sheet_name
data_array = []
for row in sheet.iter_rows(values_only=True):
    data_array.append(list(row))

try:
    for k in range(1, len(prs.slides)):
        slide = prs.slides[k]
        new_texts = data_array[k]
        print(new_texts[4])
        # continue
        image_stream = download_image(str(new_texts[4]))
        for i, shape in enumerate(slide.shapes):
            if shape.has_text_frame:
                text_frame = shape.text_frame
                # 替换文本框中的所有段落内容
                if i < len(new_texts):
                    for para in text_frame.paragraphs:
                        para.text = str(new_texts[i])
                        settings = font_settings[i]
                        for para in text_frame.paragraphs:
                            para.font.size = settings['size']
                            para.font.color.rgb = settings['color']
        left = Inches(0)  # 图片左边缘距离幻灯片左边的距离
        top = Inches(0)  # 图片上边缘距离幻灯片上边的距离
        slide.shapes.add_picture(image_stream, left, top)
except Exception as e:
    e
prs.save(fr"D:\Users\lwd\Desktop\PPt\{dir_name}\test1.pptx")